package com.cn.wanxi.servlet.user;

import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/userAdd")
public class UserAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        0.乱码处理
        req.setCharacterEncoding("UTF-8");//请求
        resp.setCharacterEncoding("UTF-8");//响应
//        1.取得页面数据
        String idString = req.getParameter("id");
//        int id=(idString==null||"".equals(idString))
        int id = 0;
        if (idString == null || "".equals(idString)) {

        } else {
            id = Integer.parseInt(idString);
        }
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//        2.封装model
        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);
        userModel.setId(id);
//        3.调用服务逻辑层
        IUserService iUserService = new UserServiceImpl();
        String result = "";
        if (id == 0) {
            result = iUserService.add(userModel);
        } else {
            result = iUserService.update(userModel);
        }
        ResultModel resultModel=new ResultModel();
        resultModel.setResult(result);

        JSONArray jsonArray = JSONArray.fromObject(resultModel);
        resp.getWriter().println(jsonArray);
//        String result = iUserService.add(userModel);
//        4.返回页面
//        req.setAttribute("result", result);
//        req.getRequestDispatcher("/back/userAdd.jsp").forward(req, resp);
    }
}
